﻿using Blog.Jwt.Utility;
using Blog.Jwt.Utility.ApiResult;
using EiiF_Blog;
using EiiFBlog.IServer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Jwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AutoizeController : ControllerBase
    {
        private readonly IAuthorService _authorService;
        public AutoizeController(IAuthorService authorService)
        {
            this._authorService = authorService;
        }

        [HttpPost("Login")]
        public async Task<ApiResult> Login(string username,string password)
        {
            string md5pass = Md5Encode.MD5Encrypt32(password);
            var repeat = await _authorService.Find(c => c.Username == username&&c.Password == md5pass);
            if (repeat == null)
            {
                return ApiResultHelper.Error("账号或密码错误");
            }
            else
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, repeat.Name),
                    new Claim("Id", repeat.Id.ToString()),
                    new Claim("Username", repeat.Username)
            };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("EiiF-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                //issuer代表颁发Token的Web应用程序，audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6000",
                    audience: "http://localhost:5000",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);
            }
        }
    }
}
